import { acceptListserver, agreeServer } from "@/servers/friendshipServer";
import { Button, Modal, message } from "antd";

import Table, { ColumnsType } from "antd/es/table";
import { useEffect, useMemo, useState } from "react";

interface AddListModalProps {
	isOpen: boolean;
	handleClose: Function;
	refreshNum: Function;
}

export interface AddFriend {
	username: string;
	reason: string;
}

interface addFriendListItemType {
	id: number;
	reason: string;
	createTime: string;
	fromUserId: number;
	toUserId: number;
	status: number;
	fromUserInfo: {
		username: string;
		nickName: string;
		headPic: string;
		email: string;
	};
}

export function AddListModal(props: AddListModalProps) {
	const [addFriendList, setAddFriendList] = useState<addFriendListItemType[]>(
		[]
	);

	const getAddFriendList = async () => {
		const res = await acceptListserver();
		const { code, data, message: msg } = res.data;
		if (code === 200 || code === 201) {
			setAddFriendList(data);
		} else {
			message.success(msg);
		}
	};

	const agreeFun = async (id: number) => {
		const res = await agreeServer(id);
		const { code, message: msg } = res.data;
		if (code === 200 || code === 201) {
			message.success(msg);
			props.refreshNum();
			props.handleClose();
		}
	};

	useEffect(() => {
		getAddFriendList();
	}, []);

	const columns: ColumnsType<addFriendListItemType> = useMemo(
		() => [
			{
				title: "用户名",
				render: (_, record) => (
					<div>{record.fromUserInfo.username}</div>
				),
			},
			{
				title: "昵称",
				dataIndex: "nickName",
				render: (_, record) => (
					<div>{record.fromUserInfo.nickName}</div>
				),
			},
			{
				title: "头像",
				dataIndex: "headPic",
				render: (_, record) => (
					<div>
						<img src={record.fromUserInfo.headPic} />
					</div>
				),
			},
			{
				title: "邮箱",
				dataIndex: "email",
				render: (_, record) => <div>{record.fromUserInfo.email}</div>,
			},
			{
				title: "申请时间",
				dataIndex: "email",
				render: (_, record) => <div>{record.createTime}</div>,
			},
			{
				title: "申请理由",
				dataIndex: "reason",
			},
			{
				title: "操作",
				render: (_, record) =>
					record.status === 0 ? (
						<div onClick={() => agreeFun(record.toUserId)}>
							<Button>同意 </Button>
						</div>
					) : (
						<div>已同意</div>
					),
			},
		],
		[]
	);

	return (
		<Modal
			title="好友申请列表"
			open={props.isOpen}
			onCancel={() => props.handleClose()}
			width={1000}
			footer={null}
		>
			<Table
				columns={columns}
				dataSource={addFriendList}
				rowKey={(record) => record.id}
				style={{ width: "1000px" }}
			/>
		</Modal>
	);
}
